import * as echarts from "echarts";
import guangxiCode from "@/assets/map/guangxi.json";
import { useEffect, useState, useRef } from "react";
import EchartsMapCss from "./EchartsMap.module.css";
function EchartsMap({ name }) {
  let currentMap = 'guangxi'
  let [areaData, setAreaData] = useState([])
  let [areaItem, setAreaItem] = useState({})
  let dituRef = useRef(null)
  let charts = useRef(null)

  useEffect(() => {
    console.log('地图组件加载', name)
    // 1. 先收集所有数据
    const newAreaItems = {};
    const newAreaData = [];

    guangxiCode.features.forEach(item => {
      newAreaItems[item.properties.name + ''] = item.properties.center;
      newAreaData.push({
        areaName: item.properties.name,
        value: (Math.random() * 100).toFixed(0)
      });
    });
    // 2. 一次性更新状态
    // setAreaItem(newAreaItems);
    setAreaData(newAreaData);

    setAreaItem({
      北海市: [109.500000, 21.80000],
      南宁市: [108.620004, 23.02402],
      崇左市: [107.353926, 22.404108],
      来宾市: [109.229772, 23.733766],
      柳州市: [109.411703, 24.914617],
      桂林市: [110.299121, 25.274215],
      梧州市: [111.100000, 23.474803],
      河池市: [108.062105, 24.695899],
      玉林市: [110.454393, 22.63136],
      百色市: [106.616285, 23.897742],
      贵港市: [110.202146, 23.593600],
      贺州市: [111.552056, 24.614141],
      钦州市: [109.000000, 22.367127],
      防城港市: [108.000000, 22.000000],
    })

    echarts.registerMap(currentMap, guangxiCode);

    // 创建/获取实例：如果实例不存在则初始化，否则复用
    charts.current = charts.current || echarts.init(dituRef.current);
    const option = {
      backgroundColor: "transparent",
      geo: [
        {
          map: currentMap,
          aspectScale: 1,
          zoom: 1.2,
          layoutCenter: ['50%', '50%'],
          layoutSize: '100%',
          show: true,
          roam: false,
          label: {
            show: false, // 各个省市县的名字
            color: '#fff',
          },
          itemStyle: {
            // 每块的样式
            areaColor: {
              type: 'linear',
              x: 1200,
              y: 0,
              x2: 0,
              y2: 0,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(3,27,78,0.75)',
                },
                {
                  offset: 1,
                  color: 'rgba(58,149,253,0.75)',
                },
              ],
              global: true, // 缺省为 false
            },
            borderColor: '#c0f3fb',
            borderWidth: 0.8,
          },
          emphasis: {
            itemStyle: {
              show: false,
              color: '#fff',
              areaColor: 'rgba(0,254,233,0.6)',
            },
            label: {
              show: false,
              color: '#fff',
            },
          },
        },
        // 重影
        {
          type: 'map',
          map: currentMap,
          zlevel: -1,
          aspectScale: 1,
          zoom: 1.2,
          layoutCenter: ['50%', '51%'],
          layoutSize: '100%',
          roam: false,
          silent: true,
          itemStyle: {
            borderWidth: 1,
            borderColor: 'rgba(58,149,253,0.8)',
            shadowColor: 'rgba(172, 122, 255,0.5)',
            shadowOffsetY: 5,
            shadowBlur: 15,
            areaColor: 'rgba(5,21,35,0.1)',
          },
        },
        {
          type: 'map',
          map: currentMap,
          zlevel: -2,
          aspectScale: 1,
          zoom: 1.2,
          layoutCenter: ['50%', '52%'],
          layoutSize: '100%',
          roam: false,
          silent: true,
          itemStyle: {
            borderWidth: 1,
            borderColor: 'rgba(58,149,253,0.6)',
            shadowColor: 'rgba(65, 214, 255,0.6)',
            shadowOffsetY: 5,
            shadowBlur: 15,
            areaColor: 'rgba(5,21,35,0.1)',
          },
        },
        {
          type: 'map',
          map: currentMap,
          zlevel: -3,
          aspectScale: 1,
          zoom: 1.2,
          layoutCenter: ['50%', '53%'],
          layoutSize: '100%',
          roam: false,
          silent: true,
          itemStyle: {
            borderWidth: 1,
            borderColor: 'rgba(58,149,253,0.4)',
            shadowColor: 'rgba(29, 111, 165,1)',
            shadowOffsetY: 15,
            shadowBlur: 10,
            areaColor: 'rgba(5,21,35,0.1)',
          },
        },
        {
          type: 'map',
          map: currentMap,
          zlevel: -4,
          aspectScale: 1,
          zoom: 1.2,
          layoutCenter: ['50%', '54%'],
          layoutSize: '100%',
          roam: false,
          silent: true,
          itemStyle: {
            borderWidth: 5,
            borderColor: 'rgba(5,9,57,0.8)',
            shadowColor: 'rgba(29, 111, 165,0.8)',
            shadowOffsetY: 15,
            shadowBlur: 10,
            areaColor: 'rgba(5,21,35,0.1)',
          },
        },
      ],
      visualMap: {
        type: 'piecewise',
        showLabel: true,
        pieces: [
          { min: 30, label: '>30' },
          { min: 11, max: 30, label: '10-30' },
          { min: 0, max: 10, label: '0-10' },
        ],
        inRange: {
          color: ['#56dabb', '#fec52c', '#f7551c']
        },
        seriesIndex: 999,
        left: 35,
        bottom: 35,
        textStyle: {
          color: "#fff",
        },
      },
      // 在右下角添加单位文案
      graphic: {
        type: 'text',
        right: '20px',    // 距离右侧 20px
        bottom: '10px',   // 距离底部 10px
        style: {
          text: '单位：个',
          fill: '#C0E9FF',   // 文字颜色
          fontSize: 20,
          fontFamily: 'Arial'
        }
      },
      // tooltip: {}, // 配置提示框，有这个配置项即可
      series: [

      ],
    };
    charts.current.setOption(option, true); //设置option
    setTimeout(() => charts.current.resize(), 0); // 下一帧强制重绘

    let option1 = Object.assign(option, {
      xAxis: [],
      yAxis: [],
      grid: [],
      series: [],
      tooltip: {
        trigger: "item",
        axisPointer: {
          type: "none",
        },
      },
    });
    areaData.forEach((item, idx) => {
      let barColor = ''
      let nodeCoord = areaItem[item.areaName];
      let coord = charts.current.convertToPixel("geo", nodeCoord);
      let itemData = []
      itemData.push(Number(item.value));
      if (item.value >= 0 && item.value <= 10) {
        barColor = '#58dabd';
      } else if (item.value > 10 && item.value <= 30) {
        barColor = '#fec018';
      } else if (item.value > 30) {
        barColor = '#f75218';
      }
      if (coord) {
        option.label = {
          show: true,
          position: 'top',
          color: '#fff',
          fontSize: 15
        }
        option.tooltip = {
          trigger: 'item',
          backgroundColor: 'rgba(50,50,50,0.7)',
          borderColor: '#333',
          borderWidth: 1,
          padding: 10,
          textStyle: {
            color: '#fff',
            fontSize: 14
          },
          formatter: function (params) {
            // params 是一个对象或对象数组
            console.log('params', params);
            return `
                数值: <span style="color:#ffcc00;font-weight:bold">${params.value}</span>
              `;
          }
        },
          option.xAxis.push({
            id: idx + item.areaName,
            gridId: idx + item.areaName,
            type: "category",
            color: 'white',
            name: item.areaName,//是否显示柱状图文字
            nameLocation: "middle",
            nameGap: 3,
            nameColor: '#fff',
            // 通过 nameTextStyle 设置颜色和样式
            nameTextStyle: {
              color: '#fff',     // 字体颜色
              fontSize: 12,      // 字体大小
              fontWeight: 'bold' // 字体粗细
            },
            splitLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            // data: titleItems,
            z: 100,
          });
        option.yAxis.push({
          id: idx + item.areaName,
          gridId: idx + item.areaName,
          type: "value",
          splitLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            show: false,
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: "red",
            },
          },
          min: 0,
          max: "dataMax",
        });
        option.grid.push({
          id: idx + item.areaName,
          width: 15,
          height: 30,
          left: coord[0] - 15,
          top: coord[1] - 15,
          z: 10,
        });
        option.series.push({
          id: idx + item.areaName,
          type: "bar",
          xAxisId: idx + item.areaName,
          yAxisId: idx + item.areaName,
          barGap: 0,
          barCategoryGap: 0,
          data: itemData,
          barWidth: 15,
          itemStyle: {
            fill: 'white',
            normal: {
              color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
                // 四个数字分别对应 数组中颜色的开始位置，分别为 右，下，左，上。例如（1,0,0,0 ）代表从右边开始渐
                // 变。offset取值为0~1，0代表开始时的颜色，1代表结束时的颜色，柱子表现为这两种颜色的渐变。
                offset: 0,
                color: '#ffffff'
              }, {
                offset: 1,
                color: barColor
              }]),
            },
            opacity: 0,
            emphasis: {
              label: {
                show: true,
              }
            },
          },
        });
      }
    });
    charts.current.setOption(option1);
    // charts.on('highlight', (params) => {
    //   console.log('悬停对象样式:', params.series[0].itemStyle);
    // });

    // 清理函数：组件卸载时销毁实例
    return () => {
      console.log('销毁实例')
      if (charts.current) {
        charts.current.dispose(); // 释放内存
        charts.current = null; // 清空引用
      }
    };
  }, [])
  return (
    <div className={EchartsMapCss.map}>
      <div className={EchartsMapCss.geo} ref={dituRef}></div>
    </div>
  )
}
export default EchartsMap